package com.songcha.library_business.api

import com.songcha.library_business.proxy.userinfo.UserInfoManager
import com.songcha.library_common.BuildConfig
import com.songcha.library_common.LibraryCommon
import com.songcha.library_common.util.DeviceUtil
import com.songcha.library_common.util.PackageUtil
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response

class MyInterceptor : Interceptor {
    private var versionName=""
    private var channel=""
    private var packageName=""
    private var deviceId=""
    private var accessDeviceEnabled = false

    companion object{
        @Volatile
        private var instance :MyInterceptor?=null

        fun getInstance():MyInterceptor{
            if(instance==null){
                synchronized(MyInterceptor::class.java){
                    if(instance==null){
                        instance=MyInterceptor()
                    }
                }
            }
            return instance!!
        }
    }

    private constructor()

    fun setAccessDeviceEnabled(enabled:Boolean){
        accessDeviceEnabled = enabled
    }

    override fun intercept(chain: Interceptor.Chain): Response {
        if(versionName.isEmpty()){
            versionName=PackageUtil.getPackageVersionName(LibraryCommon.getContext())
        }
        if(channel.isEmpty()){
            channel=PackageUtil.getUmengChannelName(LibraryCommon.getContext())
        }
        if(packageName.isEmpty()){
            packageName=PackageUtil.getPackageName(LibraryCommon.getContext())
        }
        if(deviceId.isEmpty() && accessDeviceEnabled){
            deviceId = DeviceUtil.getAndroidId(LibraryCommon.getContext())
        }

        val originalRequest:Request=chain.request()

        var hostName = ""
        if(packageName.isNotEmpty()){
            hostName = packageName.replace("com.","").replace(".","_")
        }

        val requestBuilder:Request.Builder=originalRequest.newBuilder()
            .addHeader("content-type","application/json")
            .addHeader("versionname",versionName)
            .addHeader("channel",channel)
            .addHeader("packagename",packageName)
            .addHeader("device-id",deviceId)
            .addHeader("host-app-name",hostName)

        //cannot use checkLogin(),because userinfo is not save when login
        if(UserInfoManager.isLogin && UserInfoManager.loginToken.isNotBlank()){
            if(BuildConfig.DEBUG && originalRequest.headers["token"]!=null){
                //not cover on debug for debug convenient
            }else{
                requestBuilder.addHeader("token",UserInfoManager.loginToken)
            }
        }

        val newRequest=requestBuilder.build()
        val response= chain.proceed(newRequest)

        return response

    }

}